package me.mononin.common.common.app;


import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import me.mononin.common.common.widget.convention.PlaceHolderView;

/**
 * @author  on 18-2-22.
 */

public abstract class Fragment extends android.support.v4.app.Fragment{

    protected View mRoot;
    private Unbinder rootUnbinder;
    protected PlaceHolderView mPlaceHolderView;
    // 标示是否第一次初始化数据
    protected boolean mIsFirstInitData = true;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        //在Activity与Fragment建立联系时初始化数据
        initArgs(getArguments());
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mRoot==null){
            int contentId = getContentId();
            View root = inflater.inflate(contentId,container,false);
            initWidget(root);
            mRoot = root;
        }else {
            if (mRoot.getParent()!=null){
                ((ViewGroup)mRoot.getParent()).removeView(mRoot);
            }
        }
        return mRoot;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (mIsFirstInitData) {
            // 触发一次以后就不会触发
            mIsFirstInitData = false;
            // 触发
            onFirstInit();
        }

        // 当View创建完成后初始化数据
        initData();
    }

    /**
     * 获取activity中的content资源ID
     * @return 资源ID
     */
    protected abstract int getContentId();

    /**
     * 初始化控件
     */
    protected void initWidget(View view){
        rootUnbinder = ButterKnife.bind(this,view);
    }

    /**
     * 初始化数据
     */
    protected void initData(){

    }

    /**
     * 初始化参数
     * @param bundle 初始化传递的参数
     * @return
     */
    protected void initArgs(Bundle bundle){

    }


    /**
     * 当首次初始化数据的时候会调用的方法
     */
    protected void onFirstInit() {

    }

    /**
     * 与Activity的onBackPressed联动
     * 以防止在Fragment中按返回键直接退出
     * 调用该方法实现拦截
     * @return 返回True时表示不拦截
     * 返回Flase时表示拦截，默认不拦截
     */
    public boolean onBackPressed(){
        return false;
    }

    /**
     * 设置占位布局
     *
     * @param placeHolderView 继承了占位布局规范的View
     */
    public void setPlaceHolderView(PlaceHolderView placeHolderView) {
        this.mPlaceHolderView = placeHolderView;
    }
}
